﻿package com.ricardoteix.utils.text {
	import flash.text.TextExtent;
	import flash.text.TextField;
	import flash.text.TextFormat;
	import flash.text.TextLineMetrics;
	
	/**
	 * ...
	 * @author Ricardo Teixeira
	 */
	public class TextFieldExtent{
				
		public function TextFieldExtent() {
			
		}
		
		/**
		 * Returns a TextExtent object, that contains information about a TextField dimentions to the text.
		 * @param	text
		 * @param	textFormat
		 * @return	TextExtent
		 */
		public static function getTextExtent (text:String, textFormat:TextFormat = null):TextExtent {
			var textField:TextField = new TextField ();
			
			textField.text = text;
			
			if (textFormat != null) {
				textField.defaultTextFormat = textFormat;
				textField.setTextFormat (textFormat);
			}
			var height:Number = 0;
			
			var extent:TextExtent = new TextExtent (0, 0, 0, 0, 0, 0);
			for (var i:int = 0; i < textField.numLines; i++) {
				var lineMetrics:TextLineMetrics = textField.getLineMetrics (i);
				
				if (lineMetrics.ascent > extent.ascent) {
					extent.ascent = lineMetrics.ascent;
				}
				if (lineMetrics.descent > extent.descent) {
					extent.ascent = lineMetrics.ascent;
				}
				if (lineMetrics.width > extent.width) {
					extent.width = lineMetrics.width;
					extent.textFieldWidth = lineMetrics.width + 6;
				}
				
				height += lineMetrics.height;
			}
			
			extent.height = height;
			extent.textFieldHeight = height + 6;
			
			return extent;
		}
		
	}

}